{extend name="layout/base"}
{block name='content'}
<body>
<div class="upload_box">
    <div class="addcontent_box">
        <form class="layui-form">
            <input type="hidden" name="id" id="videoId" value="{$data.id}">
            <div class="layui-form-item">
                <label class="layui-form-label">视频标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" placeholder="请输入标题" value="{$data.title}" autocomplete="off" id="title" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择栏目：</label>
                <div class="layui-input-block">
                    <select name="cid" id="videotype" class="layui-select">
                        <option value="0">请选择分类</option>
                        {foreach $type as $key=>$value }
                        <option value="{$value.cate_id}" {if $data.cid == $value.cate_id}selected{/if}>{$value.html}{$value.cate_name}
                        {/foreach}
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">缩略图：</label>
                <div class="layui-input-block">
                    <div id="defultimage">
                        <div class="public_edit_image">
                            <img src="{$data.img}" alt="" width="80px" height="80px"/>
                            <span class="close" id="delimage"></span>
                            <input type="hidden" value="{$data.img}" id="imageval">
                        </div>
                    </div>
                    <div id="photo" data-id="{$data.img}"></div>
                    <button type="button" class="layui-btn" id="files">
                        <i class="layui-icon">&#xe67c;</i>修改图片
                    </button>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">简述</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入简述" class="layui-textarea" id="brief">{$data.brief}</textarea>
                </div>
            </div>
        </form>
        <div class="layui-form-item">
            <label class="layui-form-label">上传视频</label>
            <div class="layui-input-block">
                <div id="drop_area" class="video_box">
                    <video src="{$data.address}" controls autobuffer poster="{$data.img}"></video>
                </div>
                <div class="upload">
                    <input type="hidden" id="video_address" value="{$data.address}">
                    <input type="file" name="file" onchange="uploadVideo(this)" id="file">
                    <span><i class="layui-icon">&#xe67c;</i>选择文件</span>
                </div>
                <progress value="0" max="10" id="prouploadfile"  style="width:300px;"></progress>
                <span id="persent">0%</span>
                <br/><br/>
                <button onclick="stopup()" id="stop" style="width:100px; margin-left:100px;">上传</button>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" id="submit">修改</button>
            </div>
        </div>

    </div>

</div>
<script>
    //拖拽上传开始
    //-1.禁止浏览器打开文件行为
    //拖离
    var uploadData = '';
    document.addEventListener("drop",function(e){
        e.preventDefault();
    })
    //拖后放
    document.addEventListener("dragleave",function(e){
        e.preventDefault();
    })
    //拖进
    document.addEventListener("dragenter",function(e){
        e.preventDefault();
    })
    //拖来拖去
    document.addEventListener("dragover",function(e){
        e.preventDefault();
    })
    //上传进度
    var pro = document.getElementById('prouploadfile');
    var persent = document.getElementById('persent');
    function clearpro(){
        pro.value=0;
        persent.innerHTML="0%";
    }
    //2.拖拽
    var stopbutton = document.getElementById('stop');
    var resultfile="";
    //拖拽区域
    var box = document.getElementById('drop_area');
    function uploadVideo (e) {
        //获取文件对象
        var fileList = e.files;
        //检测是否是拖拽文件到页面的操作
        if(fileList.length == 0){
            return false;
        }
        //拖拉图片到浏览器，可以实现预览功能
        //规定视频格式 in_array
        Array.prototype.S=String.fromCharCode(2);
        Array.prototype.in_array=function(e){
            var r=new RegExp(this.S+e+this.S);
            return (r.test(this.S+this.join(this.S)+this.S));
        };
        var video_type=["video/mp4","video/ogg"];
        //创建一个url连接,供src属性引用
        var fileurl = window.URL.createObjectURL(fileList[0]);
        //如果是图片
        if(fileList[0].type.indexOf('image') === 0){
            var str="<img width='200px' height='200px' src='"+fileurl+"'>";
            document.getElementById('drop_area').innerHTML=str;
            //如果是规定格式内的视频
        }else if(video_type.in_array(fileList[0].type)){
            var str="<video width='230px' height='160px' controls='controls' src='"+fileurl+"'></video>";
            document.getElementById('drop_area').innerHTML=str;
        }else{
            //其他格式，输出文件名
            var str="文件名字:"+fileList[0].name;
            document.getElementById('drop_area').innerHTML=str;
        }
        resultfile = fileList[0];
        //切片计算
        filesize= resultfile.size;
        setsize=1000*1024;
        filecount = filesize/setsize;
        //定义进度条
        pro.max=parseInt(Math.ceil(filecount));
        i =getCookie(resultfile.name);
        i = (i!=null && i!="")?parseInt(i):0
        if(Math.floor(filecount)<i){
            alert("该文件已经上传完成,请勿重复上传!");
            pro.value=i+1;
            persent.innerHTML="100%";
        }else{
            pro.value=i;
            p=parseInt(i)*100/Math.ceil(filecount)
            persent.innerHTML=parseInt(p)+"%";
        }
    }
    //3.ajax上传
    var stop=1;
    function xhr2(){
        if(stop==1){
            return false;
        }
        if(resultfile==""){
            alert("请选择文件！")
            return false;
        }
        i=getCookie(resultfile.name);
        i = (i!=null && i!="")?parseInt(i):0
        if(Math.floor(filecount)<parseInt(i)){
            alert("已经上传完成！");
            return false;
        }
        var xhr = new XMLHttpRequest();//第一步
        //新建一个FormData对象
        var formData = new FormData();
        //追加文件数据
        //改变进度条
        pro.value=i+1;
        p=parseInt(i+1)*100/Math.ceil(filecount)
        persent.innerHTML=parseInt(p)+"%";
        //进度条
        if((filesize-i*setsize)>setsize){
            blobfile= resultfile.slice(i*setsize,(i+1)*setsize);
        }else{
            blobfile= resultfile.slice(i*setsize,filesize);
            formData.append('lastone', Math.floor(filecount));
        }
        formData.append('file', blobfile);
        formData.append('blobname', i);
        formData.append('filename', resultfile.name);
        //设置响应返回的数据格式
        //post方式
        xhr.open('POST', "{:url('upload/upvideo')}"); //第二步骤
        //发送请求
        if (p == 100) {
            stopbutton.innerHTML = "完成"
        } else {
            stopbutton.innerHTML = "暂停"
        }
        xhr.send(formData);  //第三步骤
        //ajax返回
        xhr.onreadystatechange = function(){ //第四步
            if ( xhr.readyState == 4 && xhr.status == 200 ) {
                //请求成功
                if(i<filecount){
                    xhr2();
                }else{
                    i=0;
                }
                if(xhr.responseText!="not end"){
                    var data = eval("("+xhr.responseText+")")
                    if (data.code == 0) {
                        uploadData = data.data
                    }
                }else{
                    console.log('正在分片上传中('+Math.floor(filecount)+')...'+i);
                    console.log(xhr.responseText.data)
                }
            }
        };
        //设置超时时间
        xhr.timeout = 20000;
        xhr.ontimeout = function(event){
            alert('请求超时，网络拥堵！\n（如果文件已经上传完成,请忽略此消息！）');
        }
        i=i+1;
        setCookie(resultfile.name,i,1);//1天
    }
    //设置cookie
    function setCookie(c_name,value,expiredays)
    {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()+";path=/");
    }
    //获取cookie
    function getCookie(c_name)
    {
        if (document.cookie.length>0)
        {
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start!=-1)
            {
                c_start=c_start + c_name.length+1;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
    }
    function stopup(){
        if(stop==1){
            stop = 0
            xhr2();
        }else{
            stop = 1;
            stopbutton.innerHTML = "继续";
        }
    }
    layui.use(['jquery', 'form', 'element', 'upload'], function ($, form, element, upload) {
        $('#delimage').click(function () {
            var path = $('#imageval').val();
            $.ajax({
                url: "{:url('index/delImg')}",
                data: {path: path},
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg(res.msg);
                        $('#defultimage').empty();
                        uploadPic()
                    }
                }
            })
        })

        var imgIsNull = $('.public_edit_image img').attr('src')
        if (imgIsNull == '') {
            $('#defultimage').empty();
            uploadPic()

        } else {
            $('#files').click(function () {
                var path = $('#defultimage').html()
                if (path != '') {
                    layer.msg('请先删除原图')
                    return false
                }
            })
        }

        function uploadPic () {
            var uploadInst = upload.render({
                elem: '#files' //绑定元素
                ,url: '{:url(\'Upload/upfile\')}' //上传接口
                ,data: {isThumb: 1} //生成缩略图
                ,done: function(res){
                    var editPath = res.data[0]
                    // $('#files').hide();
                    $('#photo').html('<img src="' + res.data + '" alt="" width="80px" height="80px"/><span class="close" id="del"></span>');
                    $("#photo").attr("data-id",res.data);
                    // 上传图片删除
                    $('#photo #del').click(function () {
                        $.ajax({
                            type: 'post',
                            url: "{:url('index/delImg')}",
                            data: {path: editPath},
                            success: function (res) {
                                if (res.code == 0) {
                                    layer.msg(res.msg)
                                    $('#photo').empty()
                                } else {
                                    layer.msg(res.msg)
                                }
                            }
                        })
                    })
                }
                ,error: function(){
                    layer.msg('上传异常', {icon: 5});
                }
            });
        };

        $('#submit').click(function () {
            var id = $('#videoId').val()
            var title = $('#title').val().trim();
            var videotype = $('#videotype option:selected').val();
            var brief = $('#brief').val().trim();
            var imgPath =  $("#photo").data("id");
            var address = $('#video_address').val();
            if(address == '') {
                layer.msg('请上传视频')
                return false;
            }
            if (title == '') {
                layer.msg('请输入标题')
                return false;
            }
            if (videotype == 0) {
                layer.msg('请选择视频分类')
                return false;
            }
            if (brief == '') {
                layer.msg('请输入简述')
                return false;
            }
            if (imgPath == '') {
                layer.msg('请上传图片')
                return false;
            }
            if(uploadData != '') {
                address = uploadData.videoPath;
            }
            var prams = {
                id: id,
                title: title,
                address: address,
                brief: brief,
                cid: videotype,
                img: imgPath,
            }
            $.ajax({
                type: 'post',
                url: "{:url('video/edit')}",
                data: prams,
                success: function(res){
                    console.log(res)
                    location.href="{:url('video/lists')}";
                    layer.msg(res.msg, {
                        icon: res.code ===0 ? 6: 5
                    });
                }
            });

        })
    });
</script>
</body>
{/block}